package net.wenku8.reader

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.UserApi
import net.wenku8.reader.enums.KeyLoginPassword
import net.wenku8.reader.enums.KeyLoginRememberPassword
import net.wenku8.reader.enums.KeyLoginUsername
import net.wenku8.reader.service.FileService

class MainViewModel : ViewModel() {

    var initSuccess by mutableStateOf(false)

    fun initData(context : Context){
        viewModelScope.launch(Dispatchers.IO) {
            Log.i("initData", "start")
            MMKV.initialize(context)
            FileService.context = context
            initLogin()
            initSuccess = true
            Log.i("initData", "end")
        }
    }

    private fun initLogin(){
        Log.i("initLogin", "start")
        val loginUsername = MMKV.defaultMMKV().decodeString(KeyLoginUsername)
        val loginPassword = MMKV.defaultMMKV().decodeString(KeyLoginPassword)
        val loginRememberPassword = MMKV.defaultMMKV().decodeBool(KeyLoginRememberPassword, false)
        if (loginUsername != null && loginPassword != null && loginRememberPassword){
            UserApi.login(loginUsername, loginPassword)
        }
        Log.i("initLogin", "end")
    }


}
